package net.tngou.iask.action.api;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tngou.iask.action.BaseAction;
import net.tngou.iask.enums.LevelEnum;
import net.tngou.iask.pojo.Address;
import net.tngou.iask.pojo.Disease;
import net.tngou.iask.pojo.Main;
import net.tngou.iask.pojo.Main_disease;
import net.tngou.iask.pojo.POJO;
import net.tngou.iask.pojo.Survey;
import net.tngou.iask.pojo.User;
import net.tngou.iask.service.DiseaseService;
import net.tngou.iask.service.SurveyService;
import net.tngou.iask.service.UserService;
import net.tngou.iask.util.DateUtil;
import net.tngou.iask.util.DigestMD;
import net.tngou.iask.util.OAuthUtil;
import net.tngou.iask.util.StringUtil;

/**
 * 实体操作接口
 * @author tngou@tngou.net
 *
 */
public class MainApi extends BaseAction {

	/**
	 * 添加实体（系统管理员/运维）
	 */
	public void add() {
		if(user==null){
			run_nologin();return;
		}
		if(user.getRole()!=1&&user.getRole()!=2&&user.getRole()!=0){
			run_false("没有修改权限");return;
		}
		long b=0;
		Main bean = getAsk(Main.class);
		String prov=request.getParameter("prov");
		if(isEmpty(prov,bean.getName(),bean.getContacts(),bean.getTelephone(),bean.getDescription(),bean.getAddress()))
		{
			run_false("请求的参数不正确！");return;
		}
		Address address=new Address().get(new HashMap<String,Object>(){{put("name", prov);put("type", 2);}});
		if (address!=null) {
			 bean.setProvince(address.getId());
		}
		if(bean.getExpdate()==null)bean.setExpdate(DateUtil.toSqlDate(LocalDateTime.now().plusYears(1)));
		if(user.getRole()==1||user.getRole()==2)//管理员添加
		{			
			b = bean.save();
		}else //新用户审核
		{
			bean.setType(-1);
			bean.setUser(user.getId());
			b = bean.save();
		}
		if(b>0){
			saveLog(LevelEnum.operation, "添加实体信息("+bean.getId()+":"+bean.getName()+")");
			run_success(b+"");}
		else run_false("添加失败");
	}
	
	/**
	 * 修改审核（系统管理员/运维）
	 */
	public void change() {
		if(user==null){
			run_nologin();return;
		}
		if(user.getRole()!=1&&user.getRole()!=2){
			run_false("没有修改权限");return;
		}
		Main bean = getAsk(Main.class);
		Main main=bean.get(bean.getId());
		if(StringUtil.isNotEmpty(bean.getName()))main.setName(bean.getName());//名称
		if(StringUtil.isNotEmpty(bean.getLogo()))main.setLogo(bean.getLogo());//LOGO
		if(StringUtil.isNotEmpty(bean.getDescription()))main.setDescription(bean.getDescription());//描述
		if(StringUtil.isNotEmpty(bean.getAddress()))main.setAddress(bean.getAddress());//地址
		if(StringUtil.isNotEmpty(bean.getContacts()))main.setContacts(bean.getContacts());//联系人
		if(StringUtil.isNotEmpty(bean.getTelephone()))main.setTelephone(bean.getTelephone());//联系电话
		if(bean.getType()!=main.getType()){
			if(main.getType()==-1)//审核修改用户信息管理
			{
				User u = new User().get(main.getUser());
				if(u!=null){
					u.setMain(main.getId());
					u.setRole(3);//系统管理员
					u.update();
				    main.setUser(0);
				}
			}
			main.setType(bean.getType());//设置类型  1（免费版）、2（标准版）、3（高级版）、4（尊享版） -1（待审核）
		}
		if(bean.getExpdate()!=null)main.setExpdate(bean.getExpdate());//设置过期时间
		long b = main.update();
		if(b>0){
			saveLog(LevelEnum.operation, "修改实体信息("+main.getId()+":"+main.getName()+")");
			run_success("修改成功");}
		else run_false("修改失败");
	}
	
	/**
	 * 修改资料（实体管理）
	 */
	public void update() {
		if(user==null){
			run_nologin();return;
		}
		if(user.getRole()!=3&&user.getRole()!=4){
			run_false("没有添加用户权限");return;
		}
		Main bean = getAsk(Main.class);
		if(user.getMain()!=bean.getId())
		{
			run_false("没有添加用户权限");return;
		}
		Map<String, Object> map = new HashMap<>();
		if(StringUtil.isNotEmpty(bean.getName()))map.put("name", bean.getName());//名称
		if(StringUtil.isNotEmpty(bean.getLogo()))map.put("logo", bean.getLogo());//LOGO
		if(StringUtil.isNotEmpty(bean.getDescription()))map.put("description", bean.getDescription());//描述
		if(StringUtil.isNotEmpty(bean.getAddress()))map.put("address", bean.getAddress());//地址
		if(StringUtil.isNotEmpty(bean.getContacts()))map.put("contacts", bean.getContacts());//联系人
		if(StringUtil.isNotEmpty(bean.getTelephone()))map.put("telephone", bean.getTelephone());//联系电话
		String prov=request.getParameter("prov");
		if(StringUtil.isNotEmpty(prov))
		{
			 Address address=new Address().get(new HashMap<String,Object>(){{put("name", prov);put("type", 2);}});
			 if (address!=null) {
				 map.put("province", address.getId());
			}
		}
		long b = bean.update(map,bean.getId());
		if(b>0){
			saveLog(LevelEnum.operation, "修改实体信息");
			run_success("修改成功");}
		else run_false("修改失败");
	}
	
	/**
	 * 添加用户
	 */
	public void useradd() {
		if(user==null){
			run_nologin();return;
		}
		if(user.getRole()!=1&&user.getRole()!=2){
			run_false("没有修改权限");return;
		}
		User bean = getAsk(User.class);
		if(isEmpty(bean.getAccount(),bean.getPassword(),bean.getName())||bean.getMain()==0)
		{
			run_false("请求的参数不正确！");return;
		}
		POJO pojo=bean.get(
				new HashMap<String,Object>(){{
					put("account", bean.getAccount());
					put("main", bean.getMain());}});
		if(pojo!=null){
			run_false("已经存在该账号！");return;
		}
		bean.setPassword(DigestMD.MD5(bean.getPassword()));
		String access_token = OAuthUtil.Access_token(user.getAccount(),bean.getPassword(),user.getMain());
		String refresh_token = OAuthUtil.Refresh_token(user.getAccount());
		bean.setAccess_token(access_token);
		bean.setRefresh_token(refresh_token);
		bean.setRole(3);
		long b = bean.save();

		if(b>0){
			saveLog(LevelEnum.operation, "添加账号("+bean.getId()+":"+bean.getName()+")");
			run_success(b+"");//返回用户ID
			}
		else {run_false("添加失败！");return;}
	}
	/**
	 * 更新用户
	 */
	public void userupdate() {
		if(user==null){
			run_nologin();return;
		}
		if(user.getRole()!=1&&user.getRole()!=2){
			run_false("没有删除权限");return;
		}
		if(ask.getId()==0)
		{
			run_false("请求参数不存在！");return;
		}
		User u = new User().get(ask.getId());
		if(u==null)
		{
			run_false("请求数据不存在！");return;
		}
		User bean = getAsk(User.class);
		if(StringUtil.isNotEmpty(bean.getName()))u.setName(bean.getName());
		if(StringUtil.isNotEmpty(bean.getPassword()))//修改密码
		{
			u.setPassword(DigestMD.MD5(bean.getPassword()));
			String access_token = OAuthUtil.Access_token(u.getAccount(),bean.getPassword(),u.getMain());
			String refresh_token = OAuthUtil.Refresh_token(u.getAccount());
			u.setAccess_token(access_token);
			u.setRefresh_token(refresh_token);
			UserService service = new UserService();
			service.saveLogin(access_token, refresh_token, u);
			if(bean.getInit()==0)u.setInit(0);
			else u.setInit(1);
		}
		if(StringUtil.isNotEmpty(bean.getPhone()))u.setPhone(bean.getPhone());
		if(StringUtil.isNotEmpty(bean.getEmail()))u.setEmail(bean.getEmail());
		if(StringUtil.isNotEmpty(bean.getPosition()))u.setPosition(bean.getPosition());//职位	
		long b = u.update();
		if(b>0){
			saveLog(LevelEnum.operation, "修改账号信息("+u.getId()+":"+u.getName()+")");
			run_success("修改成功");}
		else run_false("修改失败");
		
	}
	/**
	 * 删除用户
	 */
	public void userdelete() {
		if(user==null){
			run_nologin();return;
		}
		if(user.getRole()!=1&&user.getRole()!=2){
			run_false("没有删除权限");return;
		}
		if(ask.getId()==0)
		{
			run_false("请求参数不存在！");return;
		}
		User u = new User().get(ask.getId());
		if(u==null)
		{
			run_false("请求数据不存在！");return;
		}
		u.setRole(-1);
		long b = u.update();
		if(b>0){
			saveLog(LevelEnum.operation, "删除账号("+u.getId()+":"+u.getName()+")");
			run_success(b+"");//返回用户ID
			}
		else {run_false("删除失败！");return;}
		
	}
	
	/**
	 * 添加实体疾病基本
	 */
	public void diseaseadd() {
		if(user==null){
			run_nologin();return;
		}
		if(user.getRole()!=3&&user.getRole()!=4){
			run_false("没有添加权限");return;
		}
		Main_disease bean = getAsk(Main_disease.class);
		if(bean.getDisease()==0)
		{
			run_false("请求参数不存在！");return;
		}
		POJO pojo = new Main_disease().get("main="+user.getMain()+" AND disease="+bean.getDisease());
		if(pojo!=null){run_false("已经添加了相关疾病！");return;}
		Disease disease = new Disease().get(bean.getDisease());
		if(disease==null)
		{
			run_false("请求数据不存在！");return;
		}
		SurveyService service = new SurveyService();
		List<Survey> list = service.getSurvey(disease.getId());
		if(list!=null&&list.size()>0)bean.setSurvey(list.get(0).getId());
		if(bean.getCycle()==0)bean.setCycle(disease.getCycle());
		if(bean.getPeriod()==0)bean.setPeriod(disease.getPeriod());
		bean.setMain(user.getMain());
		long id = bean.save();
		if(id>0){
			saveLog(LevelEnum.operation, "添加实体对应疾病信息("+bean.getId()+":"+disease.getName()+")");
			run_success(id+"");}
		else run_false("添加失败");
	}
	/**
	 * 编辑实体疾病基本
	 */
	public void diseaseupdate() {
		if(user==null){
			run_nologin();return;
		}
		if(user.getRole()!=3&&user.getRole()!=4){
			run_false("没有编辑权限");return;
		}
		Main_disease bean=getAsk(Main_disease.class);
		if(ask.getId()==0)
		{
			run_false("请求参数不存在！");return;
		}
		Main_disease main_disease = new Main_disease().get(ask.getId());
		if(main_disease==null)
		{
			run_false("请求数据不存在！");return;
		}
		if(bean.getSurvey()!=0)main_disease.setSurvey(bean.getSurvey());
		if(bean.getCycle()!=0)main_disease.setCycle(bean.getCycle());
		if(bean.getPeriod()!=0)main_disease.setPeriod(bean.getPeriod());
		long id = main_disease.update();
		if(id>0){
			saveLog(LevelEnum.operation, "修改实体对应疾病信息("+bean.getId()+")");
			run_success("修改成功");}
		else run_false("修改失败");
	}
	
	
	
}
